#include "fileimportmodule.h"
#include <QUrl>
#include <QDirIterator>
#include <QProcess>

FileImportModule::FileImportModule(PioCore * core)
    : m_core(core)
{
}

FileImportModule::~FileImportModule()
{
}

QString FileImportModule::scheme()
{
    return "file";
}

QString FileImportModule::description()
{
    return "import module that imports items from a mounted file system to the library";
}

bool FileImportModule::initialize(QString url)
{
    m_files.clear();

    QUrl u(url);
    m_path = u.toLocalFile();

    QDirIterator it(m_path, QDirIterator::Subdirectories);
    while(it.hasNext()) {
        it.next();
        QFileInfo fi = it.fileInfo();
        if(fi.isFile()) {
            m_files.append(fi.absoluteFilePath());
        }
    }

    return true;
}

int FileImportModule::count()
{
    return m_files.size();
}

QString FileImportModule::title(int i)
{
    QFileInfo fi(m_files[i]);
    return fi.fileName();
}

QPixmap FileImportModule::thumbnail(int i, QSize size)
{
    return QPixmap::fromImage(m_core->load(m_files[i], size));
}

bool FileImportModule::import(int i, QString path)
{
    QFileInfo fi(m_files[i]);
    QString target = QString("%1/%2").arg(path).arg(fi.fileName());
    int j = 1;
    while(QFile::exists(target)) {
        target = QString("%1/%2-%3.%4").arg(path).arg(fi.baseName()).arg(j++).arg(fi.completeSuffix());
    }

    QFileInfo fiTarget(target);
    if(!fiTarget.dir().exists())
        fiTarget.dir().mkpath(".");

    if(!QFile::copy(m_files[i], target))
        return false;

    m_core->add(target);

    return true;
}

bool FileImportModule::remove(int i)
{
    return QFile::remove(m_files[i]);
}

bool FileImportModule::eject()
{
#ifdef unix
    QProcess::execute("eject", QStringList() << m_path);
    return true;//r==0;
#else
    return false;
#endif
}

void FileImportModule::clear()
{
    m_files.clear();
}
